import { thin } from "../thin3.mjs";
import thin_render from "./thin_render.mjs";
export function lazyload_template({ container, template }) {
  // console.log({ container, template });
  lazyload({
    container,
    api: template.lazyload,
    query: template.query,
    success: template.success,
    error: template.error,
  });
}
export function lazyload({ container, api, query, success, error }) {
  let lazyload = document.createElement("lazyload");
  container.appendChild(lazyload);

  lazyload.thin_render = function () {
    thin(lazyload).empty();
    let pagenum = 1,
      totalpage;

    let lazyloadtriger = document.createElement("lazyloadtriger");
    container.appendChild(lazyloadtriger);

    load(pagenum);

    let io = new IntersectionObserver((entities, observer) => {
      if (entities[0].intersectionRatio > 0) {
        // io.disconnect();
        if (pagenum < totalpage) {
          load(pagenum + 1);
        }
      }
    });

    function load(pagenum) {
      thin(lazyloadtriger).empty().render({ message: "loading..." });

      thin
        .ajax({
          url: api,
          data: { ...query, ...{ pagenum } },
        })
        .done(render)
        .fail((err) => {
          console.log(err);
        });
    }

    function render(data) {
      // console.log(data);
      totalpage = data.totalpage;
      pagenum = data.pagenum;
      lazyload.thin_data = data;
      thin_render(lazyload, success);
      lazyloadtriger.thin_data = data;
      // thin(lazyloadtriger).empty().render("[[pagenum]]/[[totalpage]]");
      // thin(.render(success, data);
      thin(lazyloadtriger)
        .empty()
        .render({
          message: {
            if: data.pagenum === data.totalpage,
            then: "已经到底了！",
            else: `还有${data.totalpage - data.pagenum}页`,
          },
        });
      io.observe(lazyloadtriger);
    }
  };

  lazyload.thin_render();
}
